{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@courses_bp.route(\"/modify\", methods=[\"post\"])\n",
    "def modify_info():\n",
    "    \"\"\"\n",
    "    修改用户或模型的某些信息\n",
    "    :return:\n",
    "    \"\"\"\n",
    "    # eg: {\"table\": \"users\", \"name\": \"example\", \"field\": [\"Username\", \"Password\"], \"info\": [\"user1\", \"123123\"]}\n",
    "    table = request.json.get(\"table\").strip()\n",
    "    field = request.json.get(\"field\")\n",
    "    info = request.json.get(\"info\")\n",
    "    name = request.json.get(\"name\").strip()\n",
    "    if table == \"users\":\n",
    "        columnname = \"Username\"\n",
    "    elif table == \"models\":\n",
    "        columnname = \"Modelname\"\n",
    "    elif table == \"roles\":\n",
    "        pass\n",
    "    else:\n",
    "        columnname = \"\"\n",
    "        return jsonify({\"code\": 500, \"msg\": \"此表信息不支持修改!\"})\n",
    "\n",
    "    try:\n",
    "        sum = 0\n",
    "        for i in range(len(field)):\n",
    "            if table != \"roles\":\n",
    "                sql = \"update %s set %s = '%s' where %s = '%s'\" % (\n",
    "                    table,\n",
    "                    field[i],\n",
    "                    info[i],\n",
    "                    columnname,\n",
    "                    name,\n",
    "                )\n",
    "            else:\n",
    "                sql0 = \"select UserId from users where Username = '%s'\" % name\n",
    "                cursor.execute(sql0)\n",
    "                userid = cursor.fetchone()[0]\n",
    "                sql = \"update roles set ranks = '%s' where UserId = %s\" % (\n",
    "                    info[i],\n",
    "                    userid,\n",
    "                )\n",
    "            cursor.execute(sql)\n",
    "            sum += 1\n",
    "        db.commit()\n",
    "        print(\"sum\", sum)\n",
    "    except Exception as error:\n",
    "        import traceback\n",
    "        import sys\n",
    "\n",
    "        traceback.print_exc()\n",
    "        # print(traceback.format_exc())\n",
    "        err = sys.exc_info()[1]\n",
    "\n",
    "    if sum == len(field):\n",
    "        return jsonify({\"code\": 200, \"msg\": \"所有请求均已修改!\"})\n",
    "    elif not sum:\n",
    "        return jsonify({\"code\": 500, \"msg\": \"修改失败!\"})\n",
    "    else:\n",
    "        return jsonify({\"code\": 501, \"msg\": \"部分请求修改失败，错误代码：%s\" % err})\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
